const CryptoUtil = require('../../utils/crypto.js');
const apiClient = require('../../utils/api.js');

Page({
    data: {
        userInfo: {},
        encryptedData: '',
        decryptedData: '',
        inputText: '',
        hasUserInfo: false,
        canIUseGetUserProfile: false,
        isLoggedIn: false,
        privacyDataList: []
    },

    onLoad: function () {
        // 初始化加密工具
        const app = getApp();
        this.cryptoUtil = new CryptoUtil(app.globalData.encryptionKey);

        // 检查登录状态
        this.setData({
            isLoggedIn: app.globalData.isLoggedIn,
            userInfo: app.globalData.userInfo,
            hasUserInfo: !!app.globalData.userInfo.id
        });

        if (wx.getUserProfile) {
            this.setData({
                canIUseGetUserProfile: true
            });
        }

        // 如果已登录，加载用户数据
        if (this.data.isLoggedIn) {
            this.loadUserData();
        }
    },

    // 获取用户信息并登录
    getUserProfile: function (e) {
        wx.getUserProfile({
            desc: '用于完善会员资料',
            success: async (res) => {
                try {
                    console.log('获取用户信息成功', res);

                    // 获取openid (实际应用中需要通过wx.login获取)
                    const openid = await this.getOpenId();

                    // 调用登录API
                    const response = await apiClient.login(openid, res.userInfo);

                    if (response && response.success) {
                        // 设置令牌
                        apiClient.setToken(response.data.token);

                        // 更新本地状态
                        const app = getApp();
                        app.globalData.isLoggedIn = true;
                        app.globalData.userInfo = response.data.user;

                        this.setData({
                            userInfo: response.data.user,
                            hasUserInfo: true,
                            isLoggedIn: true
                        });

                        wx.showToast({
                            title: '登录成功',
                            icon: 'success'
                        });

                        // 加载用户数据
                        this.loadUserData();
                    }
                } catch (error) {
                    console.error('登录失败:', error);
                    wx.showToast({
                        title: '登录失败',
                        icon: 'none'
                    });
                }
            },
            fail: (res) => {
                console.log('获取用户信息失败', res);
            }
        });
    },

    // 获取OpenID (模拟)
    async getOpenId() {
        return new Promise((resolve) => {
            wx.login({
                success: (res) => {
                    if (res.code) {
                        // 实际应用中需要发送code到后端换取openid
                        // 这里使用模拟的openid
                        const mockOpenId = 'mock_openid_' + Date.now();
                        resolve(mockOpenId);
                    } else {
                        console.log('登录失败！' + res.errMsg);
                        resolve('default_openid');
                    }
                }
            });
        });
    },

    // 加载用户数据
    async loadUserData() {
        try {
            const response = await apiClient.getUserProfile();
            if (response && response.success) {
                this.setData({
                    userInfo: response.data.user,
                    decryptedData: JSON.stringify(response.data.user.decryptedData, null, 2)
                });
            }
        } catch (error) {
            console.error('加载用户数据失败:', error);
        }
    },

    // 输入框内容变化
    onInputChange: function (e) {
        this.setData({
            inputText: e.detail.value
        });
    },

    // 加密文本
    encryptText: function () {
        if (!this.data.inputText) {
            wx.showToast({
                title: '请输入要加密的文本',
                icon: 'none'
            });
            return;
        }

        const encrypted = this.cryptoUtil.encrypt(this.data.inputText);
        this.setData({
            encryptedData: encrypted
        });

        wx.showToast({
            title: '加密成功',
            icon: 'success'
        });
    },

    // 解密文本
    decryptText: function () {
        if (!this.data.encryptedData) {
            wx.showToast({
                title: '没有可解密的数据',
                icon: 'none'
            });
            return;
        }

        const decrypted = this.cryptoUtil.decrypt(this.data.encryptedData);
        this.setData({
            decryptedData: decrypted
        });

        wx.showToast({
            title: '解密成功',
            icon: 'success'
        });
    },

    // 保存加密数据到服务器
    async saveToServer() {
        if (!this.data.isLoggedIn) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            return;
        }

        if (!this.data.inputText) {
            wx.showToast({
                title: '请输入要保存的数据',
                icon: 'none'
            });
            return;
        }

        try {
            const response = await apiClient.savePrivacyData('user_text', this.data.inputText);

            if (response && response.success) {
                wx.showToast({
                    title: '保存成功',
                    icon: 'success'
                });
            }
        } catch (error) {
            console.error('保存失败:', error);
        }
    },

    // 从服务器读取加密数据
    async loadFromServer() {
        if (!this.data.isLoggedIn) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            return;
        }

        try {
            const response = await apiClient.getPrivacyData('user_text');

            if (response && response.success) {
                this.setData({
                    inputText: response.data.content,
                    decryptedData: response.data.content
                });

                wx.showToast({
                    title: '读取成功',
                    icon: 'success'
                });
            }
        } catch (error) {
            console.error('读取失败:', error);
        }
    },

    // 更新用户信息
    async updateProfile() {
        if (!this.data.isLoggedIn) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            return;
        }

        try {
            const response = await apiClient.updateUserProfile(this.data.userInfo);

            if (response && response.success) {
                wx.showToast({
                    title: '更新成功',
                    icon: 'success'
                });
            }
        } catch (error) {
            console.error('更新失败:', error);
        }
    },

    // 登出
    logout: function () {
        const app = getApp();
        app.clearLoginData();

        this.setData({
            userInfo: {},
            encryptedData: '',
            decryptedData: '',
            inputText: '',
            hasUserInfo: false,
            isLoggedIn: false
        });

        wx.showToast({
            title: '已退出登录',
            icon: 'success'
        });
    },

    // 删除账户
    deleteAccount: function () {
        if (!this.data.isLoggedIn) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            return;
        }

        wx.showModal({
            title: '确认删除',
            content: '删除账户将永久清除所有数据，此操作不可撤销',
            confirmText: '确认删除',
            confirmColor: '#ff0000',
            success: async (res) => {
                if (res.confirm) {
                    try {
                        const response = await apiClient.deleteAccount();

                        if (response && response.success) {
                            this.logout();
                            wx.showToast({
                                title: '账户已删除',
                                icon: 'success'
                            });
                        }
                    } catch (error) {
                        console.error('删除账户失败:', error);
                    }
                }
            }
        });
    }
});